package org.rich.charlesmurphy.core.transformer;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.ddevil.data.Data;
import org.rich.charlesmurphy.core.CMIds;
import org.rich.charlesmurphy.model.Request;
import org.springframework.util.StringUtils;

/**
 * @author Rich
 */
public class AccessLogTransformer extends AbstractTransformer {

	SimpleDateFormat dateParser = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss Z");

	@Override
	protected Request transformData(Data in) {
		Request r = new Request();

		/*
		 *
		CMIds.REMOTE_HOST
		CMIds.TIME
		CMIds.REQUEST_FIRST_LINE
		CMIds.STATUS
		CMIds.RESPONSE_BODY_SIZE

		 */

		r.setRemoteHost(in.getValue(CMIds.REMOTE_HOST).toString());
		r.setStartTime(parseDate(in.getValue(CMIds.TIME).toString()));
		r.setStatus(in.getValue(CMIds.STATUS).toString());
		String bodySize = (String)in.getValue(CMIds.RESPONSE_BODY_SIZE);
		if (StringUtils.hasText(bodySize)) {
			r.setResponseBodySize(Long.parseLong(bodySize));

		}
		String firstLine = in.getValue(CMIds.REQUEST_FIRST_LINE).toString();

		String[] parts = firstLine.split(" ");

		r.setMethod(parts[0]);
		r.setUrl(parts[1]);

		return r;
	}

	private Date parseDate(String inDate) {
		try {
			return dateParser.parse(inDate);
		} catch (ParseException e) {
			throw new RuntimeException("Unable to parse date.", e);
		}

	}
}
